package juc.topic;

/**
 * @description 线程交替打印 12A34B56C。。。。5152Z
 * 一个线程打印数字，一个线程打印字母，交替打印1-52个字符
 * 使用 wait() 和 notifyAll()
 */

public class CrossPrint01 {

    //创建锁对象
    private static final Object lock = new Object();

    //创建线程标志
    private static boolean isNum = true;

    public static void main(String[] args) {

        //创建数字线程
        Thread numThread = new Thread(() -> {
            //循环打印1-52个数字
            for (int i = 1; i <= 52; i+=2) {
                synchronized (lock){
                    //不是数字线程，等待并释放锁
                    while (!isNum){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    //是数字线程，打印数字
                    System.out.print(i);
                    System.out.print(i+1);
                    //切换标志
                    isNum = false;
                    //唤醒所有线程
                    lock.notifyAll();
                }
            }
        }, "numThread");

        //创建字母线程
        Thread letterThread = new Thread(() -> {
            //循环打印A-Z
            for (char i = 'A'; i <= 'Z'; i++) {
                synchronized (lock) {
                    //不是字母线程，等待并释放锁
                    while (isNum) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    //是字母线程，打印字母
                    System.out.print(i);
                    //切换标志
                    isNum = true;
                    //唤醒所有线程
                    lock.notifyAll();
                }
            }
        }, "letterThread");

        //开始线程
        numThread.start();
        letterThread.start();



    }

}

